package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.util.ServletUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author JA
 * @date: 2025/5/3
 * description:发送邮箱验证
 */
@WebServlet("/api/auth/sendEmailCode")
public class SendEmailCodeServlet extends HttpServlet {
    // 验证码缓存：email -> code
    private static final Map<String, String> codeMap = new HashMap<>();
    // 验证码生成时间：email -> timestamp(ms)
    private static final Map<String, Long> codeTimeMap = new HashMap<>();
    // 上次发送时间：email -> timestamp(ms)
    private static final Map<String, Long> lastSendTimeMap = new HashMap<>();


    // 验证码有效期 5 分钟
    private static final long CODE_EXPIRE_MILLIS = 5 * 60 * 1000;
    // 发送间隔限制 60 秒
    private static final long SEND_INTERVAL_MILLIS = 60 * 1000;

    private static final String FROM_EMAIL = "1661012607@qq.com";
    private static final String EMAIL_PASSWORD = "xecfiiqhimqxdfih";
    private static final String SMTP_HOST = "smtp.qq.com";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String email = req.getParameter("email");
        if (email == null || !email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$")) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("邮箱格式不正确"));
            return;
        }

        long now = System.currentTimeMillis();
        Long lastSendTime = lastSendTimeMap.get(email);
        if (lastSendTime != null && now - lastSendTime < SEND_INTERVAL_MILLIS) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("验证码发送太频繁，请稍后再试"));
            return;
        }

        // 生成验证码并存储
        String code = String.valueOf(new Random().nextInt(900000) + 100000);
        codeMap.put(email, code);
        codeTimeMap.put(email, now);
        lastSendTimeMap.put(email, now);

        // JavaMail 配置
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, EMAIL_PASSWORD);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("【注册验证码】");
            message.setText("您的验证码是：" + code + "，有效期5分钟。");

            Transport.send(message);
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("验证码已发送，请查收邮箱！"));
        } catch (MessagingException e) {
            e.printStackTrace();
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("邮件发送失败，请稍后再试"));
        }
    }

    /**
     * 验证邮箱验证码（检查是否正确且未过期）
     */
    public static boolean verifyCode(String email, String code) {
            if (email == null || code == null) {
                return false;
            }

            String savedCode = codeMap.get(email);
            Long sendTime = codeTimeMap.get(email);
            long now = System.currentTimeMillis();

            if (savedCode != null && savedCode.equals(code)
                    && sendTime != null && now - sendTime <= CODE_EXPIRE_MILLIS) {
                return true;
            } else {
                return false;
            }
        }
}

